package com.jiedeng.controller.index;

import com.jiedeng.controller.Rst;
import com.jiedeng.dao.IPersonRepository;
import com.jiedeng.model.Person;
import com.jiedeng.util.QiniuUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

/**
 * 公共方法
 *
 * @author zhouyb
 */
@RestController
@RequestMapping("/common/")
public class CommonController {
    private final Logger logger = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    IPersonRepository personRepository;
    @Value("${short.message.url}")
    public String shortMessageUrl;
    @Value("${short.message.username}")
    public String username;
    @Value("${short.message.password}")
    public String password;

    @Value("${config.winAppFilePath}")
    private String winAppFilePath;

    @Value("${config.linuxAppFilePath}")
    private String linuxAppFilePath;

    /**
     * 获取短信验证码
     *
     * @param phone 手机号
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getVeryCode", method = RequestMethod.POST)
    @ApiOperation(value = "修改密码短信验证")
    public Rst saveMessage(String phone) {
        Rst rst = new Rst();
        if (StringUtils.isEmpty(phone)) {
            rst.setResultCode(1);
            rst.setMsg("手机号为空");
        }

        List<Person> personList = personRepository.findByPhone(phone);
        if (personList != null && personList.size() > 0) {
          /*  String url = "http://116.213.72.20/SMSHttpService/send.aspx?";
            String sms_username = "yunchou";
            String sms_password = "yunchou";*/
            String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
            String sms_content = "【JPE系统】系统消息：验证码为：" + code + "【捷登科技】";
            System.out.println(sms_content);
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(shortMessageUrl + "username=" + username + "&password=" + password + "&mobile=" + phone + "&content=" + sms_content);
            CloseableHttpResponse response = null;
            try {
                try {
                    response = httpclient.execute(httpget);
                    //System.out.println(response.toString());
                    rst.setResultCode(0);
                    rst.setMsg(code);
                } catch (Exception e) {
                    rst.setResultCode(1);
                    rst.setMsg("用户不存在");
                    e.printStackTrace();
                    logger.error("短信发送失败", e);
                }

            } finally {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            rst.setResultCode(1);
            rst.setMsg("用户不存在");
        }
        return rst;
    }

    /**
     * 上传模板 excel
     *
     * @return
     */
    @RequestMapping("uploadFile")
    public String reportTempExcel(@RequestParam MultipartFile file) {

        String path = "";
        String fileName = file.getOriginalFilename();
        if (fileName.indexOf(File.separator) != -1) {
            fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
        }
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            path = winAppFilePath;
        } else {
            path = linuxAppFilePath;
        }
        fileName = path + fileName ;
        try {
            File newFile = new File(fileName);
            if (newFile.getParentFile() != null && !newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }
            file.transferTo(newFile);
        } catch (Exception e) {
            return "server error";
        }
        return "success";

    }
}
